package com.yjw.demo.netty.bio_chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

/**
 * 服务端处理类
 * 
 * @author yinjianwei
 * @date 2018/11/15
 */
public class ServerHandler implements Runnable {

    /**
     * 客户端列表
     */
    private List<Socket> clients;
    private Socket curClient;

    public ServerHandler(Socket curClient, List<Socket> clients) {
        super();
        this.curClient = curClient;
        this.clients = clients;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            // 不停的接收客户端消息
            while (true) {
                // 接收客户端消息，发送到所有客户端
                br = new BufferedReader(new InputStreamReader(curClient.getInputStream()));
                String message = br.readLine();
                System.out.println("服务端收到消息：" + message);
                for (Socket client : clients) {
                    PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
                    pw.println(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
